package com.iplatform.iplatformuser.privilege.api;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.iplatform.commons.pagination.Pagination;
import com.iplatform.commons.utils.CommResponse;
import com.iplatform.commons.utils.UserUtil;
import com.iplatform.iplatformuser.common.CollectionUtil;
import com.iplatform.iplatformuser.framework.springmvc.BaseController;
import com.iplatform.iplatformuser.privilege.service.inter.ISysDataService;
import com.iplatform.iplatformuser.privilege.util.RedisUtils;
import com.iplatform.module.privilege.PriManagerBean;
import com.iplatform.module.sys.SysDataBean;
import com.iplatform.module.sys.dto.SysDataTypeDto;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import java.math.BigDecimal;
import java.util.*;
import java.util.function.Predicate;
import java.util.stream.Collectors;

/**
 * 数据字典管理
 *
 * @author ld
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/sysdata")
@Api(tags = "数据字典管理类接口")
public class ApiSysdataController extends BaseController {

    @Autowired
    public ISysDataService sysDataService;
    @Autowired
    public RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    /**
     * 字典表管理列表
     *
     * @param formMap
     * @param pagination
     * @return
     */
    @ApiOperation(value = "字典表管理列表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "name", value = "名称", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "类型代码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "数据代码", required = false, paramType = "query"),
    })
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @GetMapping(value = "/list")
    public ResponseEntity<PageInfo<HashMap<String, String>>> list(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap,
                                                                  @ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination) {

        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<HashMap<String, String>> resultList = sysDataService.querySysData(formMap);
        PageInfo<HashMap<String, String>> pageInfo = new PageInfo<HashMap<String, String>>(resultList);
        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }


    /**
     * 查询类型代码和类型名称
     *
     * @return
     */
    @ApiOperation(value = "查询类型代码和类型名称")
    @GetMapping(value = "/codeAndNameList")
    public ResponseEntity<JSONObject> codeAndNameList() {
        List<HashMap<String, String>> resultList = sysDataService.queryCodeAndName();

        JSONObject allObject = new JSONObject();
        JSONArray arrayCode = new JSONArray();
        JSONArray arrayName = new JSONArray();

        for (Map<String, String> data : resultList) {
            JSONObject objectCode = new JSONObject();
            JSONObject objectName = new JSONObject();
            objectCode.put("typeCode", data.get("typeCode"));
            objectName.put("typeName", data.get("typeName"));
            arrayCode.add(objectCode);
            arrayName.add(objectName);
        }

        allObject.put("code", arrayCode);
        allObject.put("name", arrayName);

        return new ResponseEntity<>(allObject, HttpStatus.OK);
    }

    /**
     * 新增字典表
     *
     * @return
     */
    @ApiOperation(value = "新增字典表")
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", value = "id", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "类型代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeName", value = "类型名称", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "数据代码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "数据名称(也可存颜色类型的值)", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "BigDecimal", name = "ordNo", value = "数据排序码", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "BigDecimal", name = "typeOrdNo", value = "数据类型排序码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "description", value = "描述", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "dataType", value = "数据类型(0为系统，1为功能),不传默认为0", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "icon", value = "图标,typeCode为ICON_TYPE（注意大小写），code为0（零）还为默认图标", required = false, paramType = "query")
    })
    @PostMapping()
    public ResponseEntity<CommResponse> addSysData(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
        Integer codeNum = sysDataService.checkData(formMap.get("typeCode"),formMap.get("code"),null);
        if (codeNum >= 1){
            return new ResponseEntity<>(new CommResponse("该数据代码已经被使用",false),HttpStatus.BAD_REQUEST);
        }
        SysDataBean sysDataBean = new SysDataBean();
        PriManagerBean pri = UserUtil.getLoginAppUser();
        //TODO 获取当前用户
        if (pri != null) {
            sysDataBean.setCreatedBy(pri.getUserCode());
        } else {
            sysDataBean.setCreatedBy("admin");
        }
        if (StringUtils.isEmpty(formMap.get("dataType"))) {
            sysDataBean.setDataType("0");
        }

        sysDataBean.setIsDeleted("N");
        sysDataBean.setTypeCode(formMap.get("typeCode"));
        sysDataBean.setTypeName(formMap.get("typeName"));
        sysDataBean.setCode(formMap.get("code"));
        sysDataBean.setName(formMap.get("name"));
        if (formMap.get("ordNo") == null){
            sysDataBean.setOrdNo(BigDecimal.valueOf(999));
        }else {
            sysDataBean.setOrdNo(BigDecimal.valueOf(Long.parseLong(formMap.get("ordNo"))));
        }
        sysDataBean.setDescription(formMap.get("description"));
        sysDataBean.setDataType(formMap.get("dataType"));
        sysDataBean.setIcon(formMap.get("icon"));
        sysDataBean.setTypeOrdNo(BigDecimal.valueOf(Long.parseLong(formMap.get("typeOrdNo"))));
        sysDataService.insertSysData(sysDataBean);
        //从Redis中删除key
        delRedisKeys();
        return new ResponseEntity<>(new CommResponse("添加成功", true), HttpStatus.CREATED);
    }

    /**
     * 更新字典表
     *
     * @param formMap
     * @return
     */
    @ApiOperation(value = "更新字典表数据(右)")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", value = "ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "类型代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeName", value = "类型名称", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "数据代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "name", value = "数据名称", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "BigDecimal", name = "ordNo", value = "数据排序码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "description", value = "描述", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "dataType", value = "数据类型,0为系统1为功能", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "icon", value = "图标,typeCode为ICON_TYPE（注意大小写），code为0（零）为默认图标", required = false, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "dataType", value = "数据类型 0为系统，1为功能", required = false, paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping("dataModify")
    public ResponseEntity<CommResponse> update(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
        //校验
        if ("0".equals(sysDataService.findDataTypeByDataId(formMap.get("id")))) {
            return new ResponseEntity<>(new CommResponse("该数据不可修改!", false), HttpStatus.BAD_REQUEST);
        }
        //判重
        Integer codeNum = sysDataService.checkData(formMap.get("typeCode"),formMap.get("code"),formMap.get("id"));
        if (codeNum >= 1){
            return new ResponseEntity<>(new CommResponse("该数据代码已经被使用",false),HttpStatus.BAD_REQUEST);
        }

        //对排序码进行处理
        SysDataBean sysDataBean = new SysDataBean();
        sysDataBean.setOrdNo(BigDecimal.valueOf(Long.parseLong(formMap.get("ordNo"))));
        sysDataBean.setTypeCode(formMap.get("typeCode"));
        sysDataService.updateData(sysDataBean);

        PriManagerBean pri = UserUtil.getLoginAppUser();
        // TODO 获取当前用户
        if (pri != null) {
            formMap.put("updatedBy", pri.getUserCode());
        } else {
            formMap.put("updatedBy", "admin");
        }

        sysDataService.updateSysData(formMap);

        delRedisKeys();
        return new ResponseEntity<>(new CommResponse("更新成功", true), HttpStatus.OK);
    }

    @ApiOperation(value = "更新字典表类型(左)")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", value = "ID", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "类型代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "typeName", value = "类型名称", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "BigDecimal", name = "typeOrdNo", value = "数据类型排序码", required = true, paramType = "query")
    })
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping("typeModify")
    public ResponseEntity<CommResponse> updateType(@ApiParam(hidden = true) @RequestParam Map<String, String> formMap) {
        SysDataBean sysDataBean = new SysDataBean();
        sysDataBean.setTypeCode(formMap.get("typeCode"));
        sysDataBean.setTypeName(formMap.get("typeName"));
        sysDataBean.setDataId(formMap.get("id"));
        sysDataBean.setTypeOrdNo(BigDecimal.valueOf(Long.parseLong(formMap.get("typeOrdNo"))));
        sysDataService.updateType(sysDataBean);
        //删除keys
        delRedisKeys();
        return new ResponseEntity<>(new CommResponse("更新成功", true), HttpStatus.OK);
    }

    /**
     * 批量删除数据
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除数据(右)")
    @PutMapping(value = "/data")
    public ResponseEntity<CommResponse> batchDelete(@RequestParam List<String> ids) {

        sysDataService.batchDeleteSysData(ids);
        //从Redis中删除key
        delRedisKeys();
        System.out.println("删除键");
        return new ResponseEntity<>(new CommResponse("删除成功", true), HttpStatus.NO_CONTENT);
    }

    /**
     * 批量删除数据
     *
     * @param ids
     * @return
     */
    @ApiOperation(value = "批量删除数据的类型(左)")
    @PutMapping(value = "/type")
    public ResponseEntity<CommResponse> batchDeleteType(@RequestParam List<String> ids) {

        sysDataService.batchDeleteType(ids);
        //从Redis中删除key
        delRedisKeys();
        return new ResponseEntity<>(new CommResponse("删除成功", true), HttpStatus.NO_CONTENT);
    }

    /**
     * 权限状态修改
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "修改是否只读")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", value = "id", required = true, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping(value = "/setReadOnly")
    public CommResponse setReadOnly(@RequestParam String id) {

        sysDataService.setReadOnlyStatus(id);
        delRedisKeys();
        return new CommResponse("修改是否只读", true);
    }


    /**
     * 根据类型查询字典表
     *
     * @return
     */
    @ApiOperation(value = "根据类型查询字典表")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "数据类型代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "数据代码", paramType = "query", required = true)})
    @GetMapping(value = "/sysDataByType")
    public ResponseEntity<List<String>> querySysDataByType(@RequestParam String typeCode, @RequestParam(required = false) String code) {
        Map<String, String> map = CollectionUtil.getHashMap(2);
        map.put("typeCode", typeCode);
        map.put("code", code);
        List<String> list = new ArrayList<>();

        RedisUtils redisUtils = new RedisUtils(stringRedisTemplate);
        List<String> keys1 = redisUtils.keys("data:sys_data:typeCode:*");
        List<String> keys2 = redisUtils.keys("data:sys_data:code:*");
        //Redis中是否有数据
        if (keys1.size()>0 && keys2.size()>0){
            //通过key查询Set中的id
            Set<String> typeCodeIds = stringRedisTemplate.opsForSet().members("data:sys_data:typeCode:" + typeCode);
            Set<String> codeIds = stringRedisTemplate.opsForSet().members("data:sys_data:code:" + code);
            //存上面两者的交集
            Collection<Object> result = new HashSet<>();
            result.clear();
            result.addAll(typeCodeIds);
            result.retainAll(codeIds);
            List<Object> objects = stringRedisTemplate.opsForHash().multiGet("data:sys_data",result);
            List<Object> objects1 = stringRedisTemplate.boundHashOps("data:sys_data").multiGet(result);
            for (Object object : objects) {
                String s = (String) object;
                SysDataTypeDto sysDataTypeDto = JSON.parseObject(s, SysDataTypeDto.class);
                list.add(sysDataTypeDto.getCode());
            }

            return new ResponseEntity<>(list, HttpStatus.OK);
        }

        //并集,精确查询:返回数据 code
        list = sysDataService.querySysDataByType(map);
        //将数据放入Redis
        sysDataService.DataToRedis();
        return new ResponseEntity<>(list, HttpStatus.OK);
    }

    @ApiOperation(value = "查询最新同步时间信息")
//	@GetMapping(value = "/loadSycDate")
    @RequestMapping(value = "/loadSycDate", method = RequestMethod.POST)
    public ResponseEntity<JSONObject> loadSycDate() {
        List<HashMap<String, String>> resultList = sysDataService.loadSycDate();

        JSONObject allObject = new JSONObject();
        JSONArray sycDate = new JSONArray();

        for (Map<String, String> data : resultList) {
            JSONObject objectDate = new JSONObject();
            objectDate.put("syc_date", data.get("syc_date"));
            sycDate.add(objectDate);
        }

        allObject.put("syc_date", sycDate);

        return new ResponseEntity<>(allObject, HttpStatus.OK);
    }

    /**
     * 根据类型查询字典表
     *
     * @return
     */
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "数据类型代码", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "code", value = "数据代码-精确查询数据名称", paramType = "query", required = false),
            @ApiImplicitParam(dataType = "String", name = "codeName", value = "数据代码名称/代码-模糊查询", paramType = "query", required = false),
            @ApiImplicitParam(dataType = "String", name = "dataType", value = "系统或功能数据筛选", paramType = "query", required = false)
    })
    @ApiOperation(value = "根据数据类型查询字典列表(右)")
    @GetMapping(value = "/sysDataByTypeCode")
    public ResponseEntity<PageInfo<SysDataTypeDto>> querySysDataByTypeCode(@RequestParam String typeCode, String code, String codeName,String dataType,Pagination pagination) {
        //根据typeCode查询
        Set<String> ids = new HashSet<>();
        Set<String> idsResult = new HashSet<>();

        if (stringRedisTemplate.keys("data:sys_data:type*").size()>0){
            log.info("Redis中查询typtCode:{};codeName:{}",typeCode,codeName);
            List<SysDataTypeDto> list = new ArrayList<>();
            //根据typeCode查询
            if (typeCode != null || "".equals(typeCode)){
                //查出对应的所有key
                Set<String> keys = stringRedisTemplate.keys("data:sys_data:typeCode:*" + typeCode + "*");
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        ids.add(s);
                    }
                }
            }
            //根据codeName查询
            if (codeName != null || "".equals(codeName)) {
                //查出typeCode对应的所有key
                Set<String> keys = stringRedisTemplate.keys("data:sys_data:code:*" + codeName + "*");
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        if (ids.contains(s)){
                            idsResult.add(s);
                        }

                    }
                }
                //查出typeName对应的所有key
                Set<String> keys2 = stringRedisTemplate.keys("data:sys_data:name:*" + codeName + "*");
                Iterator<String> iterator2 = keys2.iterator();
                while (iterator2.hasNext()) {
                    String key = iterator2.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        if (ids.contains(s)){
                            idsResult.add(s);
                        }

                    }
                }
                ids = idsResult;
            }

            List<String> list1 = new ArrayList<>(ids);

            for (int i = 0; i < list1.size(); i++) {
                String id = list1.get(i);
                Object o = stringRedisTemplate.boundHashOps("data:sys_data").get(id);
                SysDataTypeDto sysDataTypeDto = JSONObject.parseObject(o.toString(), SysDataTypeDto.class);
                if (sysDataTypeDto.getCode() != null){
                    list.add(sysDataTypeDto);
                }
            }
            //排序
            List<SysDataTypeDto> collect = list.stream().sorted(Comparator.comparing(SysDataTypeDto::getTypeOrdNo)).collect(Collectors.toList());
            //分页
            List<SysDataTypeDto> collect1 = collect.stream().skip((pagination.getPageNum() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).collect(Collectors.toList());

            PageInfo<SysDataTypeDto> pageInfo = new PageInfo(collect1);
            int total = list.size();
            int pageSize = pagination.getPageSize();
            int pageNum = pagination.getPageNum();
            int pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
            pageInfo.setTotal(total);
            pageInfo.setPageSize(pageSize);
            pageInfo.setPageNum(pageNum);
            pageInfo.setPages(pages);
            return new ResponseEntity<>(pageInfo, HttpStatus.OK);
        }
        boolean b = sysDataService.DataToRedis();

        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<SysDataTypeDto> list = sysDataService.querySysDataByTypeCode(typeCode, code, codeName,dataType);
        PageInfo<SysDataTypeDto> pageInfo = new PageInfo(list);
        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }


    /**
     * 权限状态修改
     *
     * @param id
     * @return
     */
    @ApiOperation(value = "修改权限状态")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "id", value = "id", required = true, paramType = "query"),
            @ApiImplicitParam(dataType = "String", name = "dataType", value = "数据类型状态,0为系统，1为功能", required = true, paramType = "query")})
    @ApiResponses({@ApiResponse(code = HttpServletResponse.SC_OK, message = "成功"),
            @ApiResponse(code = HttpServletResponse.SC_CONFLICT, message = "没有做到API使用规范")})
    @PutMapping(value = "/setDataType")
    public CommResponse setDataType(@RequestParam String id, @RequestParam String dataType) {

        sysDataService.setDataType(id, dataType);
        //从Redis中删除key
        delRedisKeys();
        return new CommResponse("修改权限成功", true);
    }

    /**
     * 获取所有数据类型和名称
     *
     * @return
     */
    @ApiOperation(value = "获取所有数据类型和名称(左)")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "typeName", value = "类型名称/代码-模糊查询", required = false, paramType = "query")})
    @GetMapping(value = "/typeCodeAndNameList")
    public ResponseEntity<PageInfo<SysDataTypeDto>> typeCodeAndNameList(@ApiParam(hidden = true) @ModelAttribute(value = "pagination") Pagination pagination, @RequestParam String typeName) {
        //判断Redis中是否命中key
        Boolean keyState = stringRedisTemplate.hasKey("data:sys_data");
        log.info("data:sys_data:*  ->  {}",keyState);
        Set<String> keys = stringRedisTemplate.keys("sys_data:id:typeCode:*");
        Boolean aBoolean = keys.size() == 0 ? false:true;
        log.info("sys_data:id:typeCode:*  ->  {}",aBoolean);
        if (keyState && aBoolean){
            log.info("查询Redis");
            List<SysDataTypeDto> list = new ArrayList<>();
            //查询所有
            if ((typeName == null || "".equals(typeName)) && keys.size() > 0) {
                log.info("查询所有");
                Set<String> keys1 = stringRedisTemplate.keys("sys_data:id:typeCode:*");
                List<String> list1 = stringRedisTemplate.opsForValue().multiGet(keys1);
                for (int i = 0; i < list1.size(); i++) {
                    String id = list1.get(i);
                    Object o = stringRedisTemplate.boundHashOps("data:sys_data").get(id);
                    SysDataTypeDto sysDataTypeDto = JSONObject.parseObject(o.toString(), SysDataTypeDto.class);
                    list.add(sysDataTypeDto);

                }
                //排序
                List<SysDataTypeDto> collect = list.stream().sorted(Comparator.comparing(SysDataTypeDto::getTypeOrdNo)).collect(Collectors.toList());
                //分页
                List<SysDataTypeDto> collect1 = collect.stream().skip((pagination.getPageNum() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).collect(Collectors.toList());

                PageInfo<SysDataTypeDto> pageInfo = new PageInfo(collect1);
                int total = list.size();
                int pageSize = pagination.getPageSize();
                int pageNum = pagination.getPageNum();
                int pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
                pageInfo.setTotal(total);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPages(pages);
                return new ResponseEntity<>(pageInfo, HttpStatus.OK);
            } else {
                //按照typeName查询
                log.info("按照条件查询typeName：{}",typeName);
                Set<String> keys1 = stringRedisTemplate.keys("sys_data:id:typeCode:*" + typeName + "*");
                Set<String> keys2 = stringRedisTemplate.keys("sys_data:id:typeName:*" + typeName + "*");
                keys1.forEach( id -> {
                    //id是否存在
                    boolean contains = keys2.contains(id);
                    if (!contains){
                        keys2.add(id);
                    }
                } );

                List<String> list1 = stringRedisTemplate.opsForValue().multiGet(keys2);
                //去除重复ID
                HashSet<String> strings = new HashSet<>(list1);
                list1.clear();
                list1.addAll(strings);
                for (int i = 0; i < list1.size(); i++) {
                    String id = list1.get(i);
                    Object o = stringRedisTemplate.boundHashOps("data:sys_data").get(id);
                    SysDataTypeDto sysDataTypeDto = JSONObject.parseObject(o.toString(), SysDataTypeDto.class);
                    list.add(sysDataTypeDto);

                }
                //排序
                List<SysDataTypeDto> collect = list.stream().sorted(Comparator.comparing(SysDataTypeDto::getTypeOrdNo)).collect(Collectors.toList());
                //分页
                List<SysDataTypeDto> collect1 = collect.stream().skip((pagination.getPageNum() - 1) * pagination.getPageSize()).limit(pagination.getPageSize()).collect(Collectors.toList());

                PageInfo<SysDataTypeDto> pageInfo = new PageInfo(collect1);
                int total = list.size();
                int pageSize = pagination.getPageSize();
                int pageNum = pagination.getPageNum();
                int pages = total % pageSize == 0 ? total / pageSize : total / pageSize + 1;
                pageInfo.setTotal(total);
                pageInfo.setPageSize(pageSize);
                pageInfo.setPageNum(pageNum);
                pageInfo.setPages(pages);
                return new ResponseEntity<>(pageInfo, HttpStatus.OK);

            }
        }

        boolean b = sysDataService.DataToRedis();

        PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
        List<SysDataTypeDto> list = sysDataService.findTypeCodeAndTypeName(typeName);
        PageInfo<SysDataTypeDto> pageInfo = new PageInfo(list);
        return new ResponseEntity<>(pageInfo, HttpStatus.OK);
    }

    /**
     * 获取所有数据类型和名称
     *
     * @return
     */
    @ApiOperation(value = "获取所有数据类型和名称,不分页")
    @ApiImplicitParams({
            @ApiImplicitParam(dataType = "String", name = "typeCode", value = "数据类型代码", required = true, paramType = "query"),})
    @GetMapping(value = "/typeCodeAndNameListV2")
    public List<SysDataTypeDto> typeCodeAndNameList(@RequestParam String typeCode, String code, String codeName,String dataType) {
        //根据typeCode查询
        Set<String> ids = new HashSet<>();
        Set<String> idsResult = new HashSet<>();

        if (stringRedisTemplate.keys("data:sys_data:type*").size()>0) {
            log.info("Redis中查询typtCode:{};codeName:{}", typeCode, codeName);
            List<SysDataTypeDto> list = new ArrayList<>();
            //根据typeCode查询
            if (typeCode != null || "".equals(typeCode)) {
                //查出对应的所有key
                Set<String> keys = stringRedisTemplate.keys("data:sys_data:typeCode:*" + typeCode + "*");
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        ids.add(s);
                    }
                }
            }
            //根据codeName查询
            if (codeName != null || "".equals(codeName)) {
                //查出typeCode对应的所有key
                Set<String> keys = stringRedisTemplate.keys("data:sys_data:code:*" + codeName + "*");
                Iterator<String> iterator = keys.iterator();
                while (iterator.hasNext()) {
                    String key = iterator.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        if (ids.contains(s)) {
                            idsResult.add(s);
                        }

                    }
                }
                //查出typeName对应的所有key
                Set<String> keys2 = stringRedisTemplate.keys("data:sys_data:name:*" + codeName + "*");
                Iterator<String> iterator2 = keys2.iterator();
                while (iterator2.hasNext()) {
                    String key = iterator2.next();
                    //一个key中的所有id
                    Set<String> id = stringRedisTemplate.boundSetOps(key).members();
                    for (String s : id) {
                        if (ids.contains(s)) {
                            idsResult.add(s);
                        }

                    }
                }
                ids = idsResult;
            }

            List<String> list1 = new ArrayList<>(ids);

            for (int i = 0; i < list1.size(); i++) {
                String id = list1.get(i);
                Object o = stringRedisTemplate.boundHashOps("data:sys_data").get(id);
                SysDataTypeDto sysDataTypeDto = JSONObject.parseObject(o.toString(), SysDataTypeDto.class);
                if (sysDataTypeDto.getCode() != null) {
                    list.add(sysDataTypeDto);
                }
            }
            //排序
            list = list.stream().sorted(Comparator.comparing(SysDataTypeDto::getOrdNo)).collect(Collectors.toList());
            return list;
        }
        List<SysDataTypeDto> list = sysDataService.querySysDataByTypeCode(typeCode, code, codeName,dataType);
        sysDataService.DataToRedis();
        return list;
    }


    public void delRedisKeys(){
        sysDataService.delKeyRedis("data:sys_data");
        sysDataService.delKeyRedis("data:sys_data:*");
        sysDataService.delKeyRedis("sys_data*");
    }

}
